package com.aispeech.testcustom.view;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aispeech.aios.sdk.manager.AIOSSystemManager;
import com.aispeech.testcustom.R;
import com.aispeech.testcustom.TiApplication;
import com.aispeech.testcustom.bean.Command;
import com.aispeech.testcustom.i.CustomResultCallBack;
import com.aispeech.testcustom.i.GetDataFromXml;
import com.aispeech.testcustom.i.TiConst;
import com.aispeech.testcustom.i.XcallBack;
import com.aispeech.testcustom.utils.AssetsUtils;
import com.aispeech.testcustom.utils.PreferenceUtil;
import com.aispeech.testcustom.utils.TiLog;
import com.aispeech.testcustom.utils.UiUtils;

import java.util.ArrayList;
import java.util.List;

public class CustomCmdActivity extends AppCompatActivity implements View.OnClickListener {


    private static final int GET_INPUT = 110;
    private TextView           mTvTop;
    private ExpandableListView mLvCommand;
    private Button             mBtnWakeup, mBtnOnceAdd, mBtnClean;
    private CommandAdapter commandAdapter;

    //    ProgressDialog mProgressBar;

    public static List<Command> mlist = new ArrayList<Command>();//自定义指令集
    private String resultShow;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_back) {
            finish();
        } else if (item.getItemId() == R.id.action_print_result) {
            TiLog.d("自定义指令测试结果输出!");
            // 文件写到本地-  excel
            if (null!=mlist&&mlist.size()>0){
                UiUtils.showProgress(CustomCmdActivity.this,true,"导出excel","请稍等...");

                AssetsUtils.printRusultExcel("", mlist, new XcallBack() {
                    @Override
                    public void success() {
                        TiLog.d("excel 导出成功");
                        showTitleInfo("导出成功");
                        UiUtils.showProgress(CustomCmdActivity.this,false,"","");
                    }

                    @Override
                    public void fail() {
                        TiLog.d("excel 导出失败");
                        showTitleInfo("导出失败");
                        UiUtils.showProgress(CustomCmdActivity.this,false,"","");
                    }
                },TiConst.CUSTOM_RESULT_EXCEL_NAME , "自定义指令接口测试结果");
            }else{
                Toast.makeText(CustomCmdActivity.this,"没有可以导出的内容!",Toast.LENGTH_SHORT).show();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == GET_INPUT) {
            if (resultCode == RESULT_OK) {

                Bundle extras = data.getExtras();
                String[] inputs = extras.getStringArray("getInput");

                if (inputs != null && inputs.length > 0) {
                    //奇葩注册中url默认写死为/customize/freak/test
                    //                    Command c = new Command();
                    //                    c.setCommand("/customize/freak/test");
                    //                    c.setKeywords(inputs);
                    //                    //                    mlist.add(c);
                    //
                    //                    mLvCommand.requestLayout();
                    //                    mLvCommand.deferNotifyDataSetChanged();
                    //
                    //                    //注册奇葩指令
                    //                    List<com.aispeech.aios.sdk.bean.Command> l = new
                    // ArrayList<com.aispeech.aios
                    //                            .sdk.bean.Command>();
                    //                    l.add(new com.aispeech.aios.sdk.bean.Command
                    // ("/customize/freak/test", inputs));
                    //                    AIOSCustomizeManager.getInstance().regCommands(l);

                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_interface_test);
        TiLog.d("onCreate start customCmd test");

        mTvTop = (TextView) findViewById(R.id.main_tv_top);
        mBtnWakeup = (Button) findViewById(R.id.main_btn_wakeup);
        mBtnClean = (Button) findViewById(R.id.main_btn_clean_cmd);
        mBtnOnceAdd = (Button) findViewById(R.id.main_btn_add_once_more);

        mLvCommand = (ExpandableListView) findViewById(R.id.main_lv_command);
        commandAdapter = new CommandAdapter();
        mLvCommand.setAdapter(commandAdapter);

        initEvent();

        //读取自定义指令并在服务中注册
        getCmdListAndRegister();


    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            TiLog.d("handleMessage: " + (String) msg.obj);
            switch (msg.what) {
                //                case TiConst.MSG_REC_RESULT:
                //                    String result = (String) msg.obj;
                //                    mTvTop.setText(result);
                //                    break;
                case MSG_UPDATE_ADAPTER:
//                    mLvCommand.setAdapter(commandAdapter);
                    commandAdapter.notifyDataSetChanged();
                    break;
                case READ_FILE_ERR:
                    //rere不变,下次点击还是重新注册 , 成功了才取反 .
//                    mBtnClean.setText("重新注册");
                    break;
            }
        }
    };

    private void initEvent() {

        mBtnWakeup.setOnClickListener(this);
        mBtnClean.setOnClickListener(this);
        mBtnOnceAdd.setOnClickListener(this);
        mLvCommand.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i,
                                        int i1, long l) {

                Log.d("test", "onChildClick: url" + i + "    item:" + i1 + "   id:" + l);

                // 返回值
                // true:不往下执行
                return false;
            }
        });
    }

    /**
     * 读取自定义指令
     */
    private void getCmdListAndRegister() {
        UiUtils.showProgress(CustomCmdActivity.this, true, "指令注册中", "请稍候...");
        if (!PreferenceUtil.SettingPreference.isInitInApplication(CustomCmdActivity.this)) {
            TiLog.w("not init aios sdk!");
            showTitleInfo("语音还没初始化,重启应用后测试!!");
            UiUtils.showProgress(CustomCmdActivity.this, false, "", "");

        } else {
            if (null == TiApplication.getIService()) {
                TiLog.e("no bridgeService!!");
                showTitleInfo("语音服务没启动或者挂掉了!!!");
                UiUtils.showProgress(CustomCmdActivity.this, false, "", "");
            } else {
                AssetsUtils.readCommandFormXML("", new GetDataFromXml() {
                    @Override
                    public void success(List list) {
                        TiLog.d("读取自定义指令成功");
                        showTitleInfo("读取自定义指令成功");
//                        rere = false;//下次点击则清除指令
                        mlist = list;

                        //注册自定义指令给aios
                        TiApplication.getIService().injectCmdCallback(new CustomResultCallBack() {
                            @Override
                            public void setResultBack(String s) {
                                //获取到了自定义指令识别回调
                                TiLog.d("自定义指令回调识别结果:" + s);
                                showTitleInfo(s);
                            }
                        });
                        TiApplication.getIService().registerCmd(AssetsUtils.convertList4Register
                                (list));

                        Message msg = Message.obtain();
                        msg.what = MSG_UPDATE_ADAPTER;
                        handler.sendMessage(msg);

                        UiUtils.showProgress(CustomCmdActivity.this, false, "", "");
                    }

                    @Override
                    public void fail(int errorid) {

                        TiLog.e("读取自定义指令失败:" + errorid);
                        String err = "";
                        switch (errorid) {
                            case TiConst.IO_ERROR:
                                err = "文件读取失败";
                                break;
                            case TiConst.PARSER_ERROR:
                                err = "文件解析失败";
                                break;
                            case TiConst.PATH_ERROR:
                                err = "读取路径有误";
                                break;
                        }

                        showTitleInfo(err);

                        UiUtils.showProgress(CustomCmdActivity.this, false, "", "");
                    }
                });
            }
        }
    }



    private final int READ_FILE_ERR      = 1;
    private final int MSG_UPDATE_ADAPTER = 2;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("test", "onDestroy!");
        if (null != TiApplication.getIService()) {
            TiApplication.getIService().cleanRegisterCmd(true);
        }

    }

    @Override
    public void onClick(View view) {

        if (view == mBtnWakeup) {
            //wakeup aios
            TiLog.i("wakeup aios");
            AIOSSystemManager.getInstance().startInteraction();
        }else if (null == TiApplication.getIService()) {
                showTitleInfo("相关服务没有正常运行 ,请退出后重试!!!");
        } else{
            if (view == mBtnClean){
                TiLog.d("清除自定义指令!");
                TiApplication.getIService().cleanRegisterCmd(false);

                mlist.clear();
                commandAdapter.notifyDataSetChanged();

            }else if (view == mBtnOnceAdd) {
                //add again
                TiLog.d("继续注册自定义指令!");
                getCmdListAndRegister();
            }
        }

    }

    private void showTitleInfo(final String info) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvTop.setVisibility(View.VISIBLE);
                mTvTop.setText(info);

            }
        });

    }

    private class CommandAdapter extends BaseExpandableListAdapter {

        @Override
        public int getGroupCount() {
            if (null != mlist) {
                return mlist.size();
            }
            return 0;
        }

        @Override
        public int getChildrenCount(int i) {
            if (null != mlist) {
                Command command = mlist.get(i);
                if (null != command) {

                    return command.getKeywords() == null ? 0 : command.getKeywords
                            ().size();
                }
            }
            return 0;
        }

        @Override
        public Object getGroup(int i) {
            if (null != mlist) {
                return mlist.get(i);
            }
            return null;
        }

        @Override
        public Object getChild(int i, int i1) {
            if (null != mlist) {
                Command command = mlist.get(i);
                if (null != command) {
                    return command.getKeywords() == null ? null : command
                            .getKeywords();
                }
            }
            return null;
        }

        @Override
        public long getGroupId(int i) {
            return i;
        }

        @Override
        public long getChildId(int i, int i1) {
            return i1;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
            GroupViewHolder holder = null;
            if (null == view) {
                view = View.inflate(CustomCmdActivity.this, R.layout.item_group, null);
                holder = new GroupViewHolder();
                view.setTag(holder);
                holder.tvTitle = (TextView) view.findViewById(R.id.item_group_tv_title);

            } else {
                holder = (GroupViewHolder) view.getTag();
            }
            holder.tvTitle.setText(mlist.get(i).getCommand());
            return view;
        }

        @Override
        public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
            final int groupi = i;
            final int childi = i1;
            ChildViewHolder holder = null;
            if (null == view) {
                view = View.inflate(CustomCmdActivity.this, R.layout.item_child, null);
                holder = new ChildViewHolder();
                view.setTag(holder);
                holder.tvName = (TextView) view.findViewById(R.id.item_child_cmd);
                holder.checkBox = (CheckBox) view.findViewById(R.id.item_child_cb);

            } else {
                holder = (ChildViewHolder) view.getTag();
            }

            String s = mlist.get(i).getKeywords().get(i1).getCmd();
            holder.tvName.setText(s);
            holder.checkBox.setOnCheckedChangeListener(new MyListener
                    (i, i1));
            holder.checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mlist.get(groupi).getKeywords().get(childi)
                            .isCheckResult()) {
                        mlist.get(groupi).getKeywords().get(childi)
                                .setCheckResult(false);
                    } else {
                        mlist.get(groupi).getKeywords().get(childi)
                                .setCheckResult(true);
                    }
                }
            });

            //now no chaos
            holder.checkBox.setChecked(!mlist.get(i).getKeywords()
                    .get(i1)
                    .isCheckResult());

            return view;
        }

        @Override
        public boolean isChildSelectable(int i, int i1) {
            return true;
        }
    }

    private class GroupViewHolder {
        TextView tvTitle;
    }

    private class ChildViewHolder {
        TextView tvName;
        CheckBox checkBox;
    }

    private class MyListener implements CompoundButton.OnCheckedChangeListener {
        int groupPosition, childPosition;

        public MyListener(int gp, int cp) {
            this.groupPosition = gp;
            this.childPosition = cp;
        }

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            Log.d("test", "onCheckedChanged: " + "groupPosition:" + groupPosition + "xxx" +
                    "childposition:" + childPosition + "xxx" + "ok:" + b);
            mlist.get(groupPosition).getKeywords().get(childPosition)
                    .setCheckResult(b);
        }
    }
}
